<template>
  <el-table :data="tableData" border :span-method="arraySpanMethod">
    <el-table-column prop="id" label="id" />
    <el-table-column prop="name" label="Name" />
    <el-table-column prop="amount1" label="amount1" />
    <el-table-column prop="amount2" label="amount2" />
    <el-table-column prop="amount3" label="amount3" />
  </el-table>
</template>

<script setup>
const spanArr = ref([]); //用于存放每一行记录的合并数
const pos = ref(0);
const tableData = [
  {
    id: "2012-12-12",
    name: "Tom",
    amount1: "234",
    amount2: "3.2",
    amount3: 10,
  },
  {
    id: "2012-12-12",
    name: "Jim",
    amount1: "165",
    amount2: "4.43",
    amount3: 12,
  },
  {
    id: "2012-12-13",
    name: "Smith",
    amount1: "165",
    amount2: "4.43",
    amount3: 12,
  },

  {
    id: "2012-12-12",
    name: "Tom",
    amount1: "324",
    amount2: "1.9",
    amount3: 9,
  },
  {
    id: "2012-12-13",
    name: "Smith",
    amount1: "621",
    amount2: "2.2",
    amount3: 17,
  },
  {
    id: "2012-12-13",
    name: "Smith",
    amount1: "539",
    amount2: "4.1",
    amount3: 15,
  },
];
onMounted(() => {
  tableData.sort(sortFn);
  getSpanArr(tableData);
});
//先根据id排序再根据name排序
const sortFn = (a, b) => {
  if (a.id != b.id) {
    return a.id.localeCompare(b.id);
  }
  if (a.name != b.name) {
    return a.name.localeCompare(b.name);
  }
};

/*getSpanArr(data)方法 data就是我们从后台拿到的数据，通常是一个数组；
spanArr是一个空的数组，用于存放每一行记录的合并数；
pos是spanArr的索引。
如果是第一条记录（索引为0），向数组中加入１，并设置索引位置；
如果不是第一条记录，则判断它与前一条记录是否相等，
如果相等，则向spanArr中添入元素0，并将前一位元素＋１，表示合并行数＋１，
以此往复，得到所有行的合并数，0即表示该行不显示*/
const getSpanArr = (data) => {
  for (var i = 0; i < data.length; i++) {
    if (i === 0) {
      spanArr.value.push(1);
      pos.value = 0;
    } else {
      // 判断与上一个元素是否相等
      if (data[i].id === data[i - 1].id && data[i].name === data[i - 1].name) {
        spanArr.value[pos.value] += 1;
        spanArr.value.push(0);
      } else {
        spanArr.value.push(1);
        pos.value = i;
      }
    }
    // console.log(spanArr.value);
  }
};
/**
 * 合并行或列的计算方法
 * @param row 当前行
 * @param column 当前列
 * @param rowIndex 当前行索引
 * @param columnIndex 当前列索引
 */
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0 || columnIndex === 1) {
    const _row = spanArr.value[rowIndex]; //获取当前行合并数
    const _col = _row > 0 ? 1 : 0; //列合并数
    console.log(`rowspan:${_row} colspan:${_col}`);
    return {
      rowspan: _row,
      colspan: _col,
    };
  }
};
</script>
